package com.lg.partition39;

import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * @author `RKC`
 * @date 2022/5/8 15:20
 */
public class P3842TJOI2007_线段_最短路 {

    private static final int N = 40010, M = 2 * N, INF = 0x3f3f3f3f;
    private static int[] h = new int[N], e = new int[M], ne = new int[M], w = new int[M];
    private static int[] dist = new int[N], l = new int[N], r = new int[N];
    private static PriorityQueue<Node> heap = new PriorityQueue<>(N * 2);
    private static int n, id = 1, idx = 0;

    private static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    private static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        n = nextInt();
        Arrays.fill(h, -1);
        for (int i = 1; i <= n; i++) {
            l[i] = nextInt(); r[i] = nextInt();
            if (i == 1) {
                add(1, ++id, r[i] - 1 + r[i] - l[i]);
                add(1, ++id, r[i] - 1);
            } else {
                id++;
                //不是第一行，需要对前面两个点到当前线段的左端点进行建图
                add(id - 2, id, Math.abs(r[i] - l[i - 1]) + r[i] - l[i] + 1);
                add(id - 1, id, Math.abs(r[i] - r[i - 1]) + r[i] - l[i] + 1);
                //前一行的两个点对当前线段的右端点进行建图
                id++;
                add(id - 3, id, Math.abs(l[i] - l[i - 1]) + r[i] - l[i] + 1);
                add(id - 2, id, Math.abs(l[i] - r[i - 1]) + r[i] - l[i] + 1);
            }
        }
        //最后两个点向终点的建图
        id++;
        add(id - 2, id, n - l[n]);
        add(id - 1, id, n - r[n]);
        writer.println(dijkstra(1));
        writer.flush();
    }

    private static int dijkstra(int s) {
        Arrays.fill(dist, INF);
        dist[s] = 0;
        heap.add(new Node(s, 0));
        while (!heap.isEmpty()) {
            int u = heap.poll().u;
            if (u == id) return dist[u];
            for (int i = h[u]; i != -1; i = ne[i]) {
                int v = e[i];
                if (dist[v] > dist[u] + w[i]) {
                    dist[v] = dist[u] + w[i];
                    heap.add(new Node(v, dist[v]));
                }
            }
        }
        return -1;
    }

    private static void add(int a, int b, int c) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx;
        w[idx++] = c;
    }

    private static class Node implements Comparable<Node> {
        private int u, d;

        public Node(int u, int d) {
            this.u = u;
            this.d = d;
        }

        @Override
        public int compareTo(Node o) {
            return Integer.compare(d, o.d);
        }
    }

    private static int nextInt() throws IOException {
        tokenizer.nextToken();
        return (int) tokenizer.nval;
    }
}
